package com.winning.pmph.ctrl;

import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.UploadFileUtil;
import com.winning.pmph.vo.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * @author wu_di@winning.com.cn
 * @date 2021/1/13
 */
@Api(value = "视屏上传播放")
@Slf4j
@RestController
@RequestMapping("/pmph/action/video")
public class VideoCtrl  {

    @ApiOperation(value = "play", notes = "播放视屏接口")
    @GetMapping("play")
    public void play(HttpServletResponse response, String filename) throws IOException {
        String tempFilePath = ApplicationContextUtil.BASE_DOWN_FORDER + filename;
        File file = new File(tempFilePath);
        response.setContentType("video/mp4");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Range", "" + (file.length() - 1));
        response.setHeader("Accept-Ranges", "bytes");
        FileUtils.copyFile(file, response.getOutputStream());
    }

    @ApiOperation(value = "upload", notes = "上传视频接口")
    @PostMapping("upload")
    public FileVo upload(MultipartFile file, @RequestParam String uploadPath) {
        if (StringUtils.isEmpty(uploadPath)) {
            throw new RuntimeException("存储路径为空");
        }
        log.debug("上传视频");
        String path = ApplicationContextUtil.BASE_DOWN_FORDER + uploadPath;
        log.debug("上传路径：" + path);
        String storedName = UploadFileUtil.uploadFile(file, path, true);
        return new FileVo("/pmph/action/video/play?filename=" + uploadPath + "/" + storedName);
    }
}
